import logging
from tortoise import Tortoise

TORTOISE_ORM = {
    "connections": {
        "default": {
            "engine": "tortoise.backends.mysql",
            "credentials": {
                "host": "192.168.1.12",
                "port": 3306,
                "user": "root",
                "password": "root",
                "database": "test_db",
                "charset": "utf8mb4",
            }
        }
    },
    "apps": {
        "models": {
            "models": ["app.models", "aerich.models"],
            "default_connection": "default",
        }
    },
    "use_tz": False,
}

async def init_db():
    try:
        await Tortoise.init(config=TORTOISE_ORM)
        await Tortoise.generate_schemas()  # 自动创建表
        logging.info("Database initialized successfully")
    except Exception as e:
        logging.error(f"Database initialization failed: {e}")
        raise

async def close_db():
    """关闭数据库连接"""
    await Tortoise.close_connections()
    logging.info("Database connections closed")
